package com.viu.technology.service.message;

import com.alibaba.fastjson.JSONObject;
import com.viu.technology.dto.ChatMessage;
import com.viu.technology.dto.IMMessage;
import com.viu.technology.mapper.MessageMapper;
import com.viu.technology.util.ChannelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Service
public class MessageServiceImpl implements MessageService{

    private static final Logger log = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Queue chatDurableQueue;

    @Autowired
    private RabbitAdmin rabbitAdmin;

    @Autowired
    private ChannelUtil channelUtil;


    @Override
    public boolean durableChatMessage(ChatMessage message) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int i=messageMapper.insert(message);

        return i > 0 ? true : false;
    }

    /**
     * 获取用户未读消息，并将消息发送给用户，以及持久化消息
     * @param userId
     * @return
     * @throws InterruptedException
     */
    //@Async("rabbitListenerExecutor")
    @Override
    public boolean getUnreadMessage(String userId) throws InterruptedException {
        log.info("开始获取用户ID ："+userId+" 的未读消息");
        String queueName = "queue.chat.unread." + userId;
        //根据queueName获取Rabbit队列中对应的队列名，如果不存在该队列名则返回null
        Properties properties = rabbitAdmin.getQueueProperties(queueName);
        String qn= null;
        try {
            qn = (String) properties.get(RabbitAdmin.QUEUE_NAME);
            if (qn != null) {
                //获取有多少未读消息
                int messageCount = (int) properties.get(RabbitAdmin.QUEUE_MESSAGE_COUNT);
                for (int i = 0; i < messageCount; i++) {
                    String msg= (String) rabbitTemplate.receiveAndConvert(queueName) ;
                    IMMessage imMessage = JSONObject.parseObject(msg, IMMessage.class);
                    channelUtil.sendMsg(userId, imMessage.toString());

                    rabbitTemplate.convertAndSend(chatDurableQueue.getName(), imMessage.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;

    }
}
